﻿using System.Collections.Generic;
using LogSystem;
using UnityEngine;
using XLua;

namespace com.yoozoo.gta.Extension
{
    public class NativeKeyboardWidget : MonoBehaviour
    {
        private List<LuaFunction> luaCallbacks = new List<LuaFunction>();
        
#if !UNITY_EDITOR && UNITY_ANDROID
        private AndroidJavaClass javaClass;
#endif
        private int keyboardHeight = 0;

        public void AddKeyboardHeightChangedListener(LuaFunction callback)
        {
            this.luaCallbacks.Add(callback);
        }

        private void Start()
        {
#if !UNITY_EDITOR && UNITY_ANDROID
            this.javaClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
#endif
        }

        private int GetKeyboardHeight()
        {
#if !UNITY_EDITOR
        #if UNITY_ANDROID
            AndroidJavaObject View = this.javaClass.GetStatic<AndroidJavaObject>("currentActivity").
                Get<AndroidJavaObject>("mUnityPlayer").Call<AndroidJavaObject>("getView");

            using (AndroidJavaObject Rct = new AndroidJavaObject("android.graphics.Rect")) {
                View.Call("getWindowVisibleDisplayFrame", Rct);
                return Screen.height - Rct.Call<int>("height");
            }
        #elif UNITY_IOS
            return (int)TouchScreenKeyboard.area.height * Display.main.systemHeight / Screen.height;
        #else
            return 0;
        #endif
#endif
            return 0;
        }

        private void Update()
        {
            var h = GetKeyboardHeight();
            // 三星note8自带键盘会有高度为负数的情况
            if (h < 0)
                h = 0;
            
            if (h == this.keyboardHeight)
                return;

            this.keyboardHeight = h;
            OnKeyboardHeightChanged(h);
            Debug.Log(LogModule.Chat, "Keyboard height: " + h);
        }

        private void OnKeyboardHeightChanged(int height)
        {
            for (int i = 0; i < this.luaCallbacks.Count; i++)
                this.luaCallbacks[i].Action(height);
        }
    }
}